<template>
	<view style="padding-bottom: 20px;">
		
		<van-cell-group>
		  <van-cell title="申请人" :value="detailData.applyUserName" />
		  <van-cell title="科室" :value="detailData.applyPartmentName" />
		 <van-cell title="用车人" :value="detailData.passengers[0].name" />
		 <van-cell title="申请时间" :value="createTime" />
		 <van-cell title="用车人电话" :value="detailData.passengers[0].tel" />
		  <van-cell title="用车类型" :value="orderType" />
		  <van-cell title="申请编号" :value="detailData.id" />
		</van-cell-group>
		
		<van-cell-group title="申请状态">
		  <van-cell title="当前状态" :value="orderStatusText" />
		</van-cell-group>
		
		<van-cell-group title="用车明细">
			<template v-if="detailData.orderType == 'yuyue'">
				<van-cell title="发车时间" :value="dataTime"/>
				<!-- :value="detailData.setoffTime" -->
				<van-cell title="返回时间" :value="backTime" />
				<van-cell title="乘坐人数" :value="detailData.passengersNum" />
				<!-- 进入的功能角色和状态 -->
				<!-- 进入的功能角色和状态 -->
				<!-- <van-field v-if="role == 'controller' && detailData.status == 'allowed'" label="用车数量"  type="digit" :value="detailData.requstCarNum" input-align="right" data-type="carNum" right-icon="edit"
				 @change="onChange" placeholder="请输入用车数量" /> -->
				 <van-cell title="用车数量" :value="detailData.requstCarNum" />
				 
				<van-cell title="乘车地点" :value="detailData.setoffAddress" />
				<van-cell title="到达地点" :value="detailData.arrivalAddress" />
				<van-cell title="用车事由" :value="detailData.applyReason" />
				<van-cell title="接受拼车" :value="detailData.allowCarpooling == 'yes' ? '是' : '否'" />
			</template>
			<template v-if="detailData.orderType == 'jieji'">
				<van-cell title="航班号" :value="detailData.airNumber" />
				<van-cell title="乘坐人数" :value="detailData.passengersNum" />
				<!-- 进入的功能角色和状态 -->
			<!-- 	<van-field v-if="role == 'controller' && detailData.status == 'allowed'" label="用车数量"  type="digit" :value="detailData.requstCarNum" input-align="right" data-type="carNum" right-icon="edit"
				 @change="onChange" placeholder="请输入用车数量" /> -->
				 <van-cell title="用车数量" :value="detailData.requstCarNum" />
				<van-cell title="到达地点" :value="detailData.arrivalAddress" />
				<van-cell title="备注" :value="detailData.note" />
			</template>
			<template v-if="detailData.orderType == 'songji'">
				<van-cell title="航班号" :value="detailData.airNumber" />
				<van-cell title="乘坐人数" :value="detailData.passengersNum" />
				<!-- 进入的功能角色和状态 -->
				<!-- <van-field v-if="role == 'controller' && detailData.status == 'allowed'" label="用车数量"  type="digit" :value="detailData.requstCarNum" input-align="right" data-type="carNum" right-icon="edit"
				 @change="onChange" placeholder="请输入用车数量" /> -->
				 <van-cell title="用车数量" :value="detailData.requstCarNum" />
				<van-cell title="乘车地点" :value="detailData.setoffAddress" autosize />
				<van-cell title="备注" :value="detailData.note" />
			</template>
			<van-cell title="里程(KM)" :value="detailData.totalKM" />
		</van-cell-group>
		
		<!-- <van-cell-group title="审核流程">
			<view class="flow-container">
				<m-flow-item/>
				<m-flow-item/>
				<m-flow-item/>
			</view>
		</van-cell-group> -->
		
		<van-cell-group v-if="detailData.status == 'refused'" title="拒绝理由">
			<view class="refuse-container">
				<text>{{detailData.refuseReason}}</text>
			</view>
		</van-cell-group>
		
		<view style="margin-top: 20px;">
		</view>
		
		<template v-if="role == 'controller'">
			<view style="margin-top: 20px;">
				<m-add-route :items="routeItems" :orderid="detailData.id"></m-add-route>
			</view>
		</template>
		
		<van-cell-group v-if="role == 'user'" v-for="(item,index) in detailData.lstCD" :key="index" :title="'行程' + (index + 1)">
			<!-- <van-cell title="车辆照片" is-link value="点击查看" @click="onClickShow" /> -->
			<van-cell title="车辆" :value="`${item.car.chepai}`" />
			<van-cell title="司机" @click="onCallPhone" :data-tel="item.driver.tel" :value="`${item.driver.name} ${item.driver.tel}`" />
		</van-cell-group>
		
		<view style="margin-top: 20px;">
		</view>
		
		<template v-if="role == 'user'">
			<view v-if="detailData.status == 'created'" class="wrap">
				<van-button custom-class="left-button" :color="primaryColor" :square="true" size="normal" @click="onSendMsg('noticeReview')">提醒审核</van-button>
				<van-button custom-class="center-button" :color="warningColor" :square="true" size="normal" @click="updata">信息修改</van-button>
				<van-button custom-class="right-button" :color="secondaryColor" :square="true" size="normal" @click="cancelOrder">取消申请</van-button>
			</view>
			
			<view v-if="detailData.status == 'allowed'">
				<van-button custom-class="left-button" :color="primaryColor" :square="true" size="normal" @click="onSendMsg('noticeDispatch')">提醒调度</van-button>
				<!-- <van-button custom-class="center-button" :color="warningColor" :square="true" size="normal" @click="updata">信息修改</van-button> -->
				<van-button custom-class="right-button" :color="secondaryColor" :square="true" size="normal" @click="cancelOrder">取消申请</van-button>
			</view>
			
			<view v-if="detailData.status == 'dispatched'">
				<van-button custom-class="between-button"  :square="true" size="normal" @click="updDemandInOrder" >修改需求</van-button>
			</view> 
			<!-- <view v-if="detailData.status == 'dispatched'">
				<van-button custom-class="left-button"  :color="primaryColor" :square="true" size="normal" @click="onConnectDriver" icon="phone" block>联系司机</van-button>
				<van-button custom-class="center-button" :color="warningColor" :square="true" size="normal" @click="updata">信息修改</van-button>
				<van-button custom-class="right-button" :color="secondaryColor" :square="true" size="normal" @click="cancelOrder">取消申请</van-button>
			</view> -->
			
			<!-- <view v-if="detailData.status == 'travelStarted'">
				<van-button custom-class="left-button" :color="primaryColor" :square="true" size="normal" @click="onConnectDriver" block icon="phone">联系司机</van-button>
			</view> -->
			
			<view v-if="detailData.status == 'adminComfirmed'">
				<van-button :color="primaryColor" :square="true" size="normal" custom-class="large-mode" @click="onFinishOrder">确认完成</van-button>
			</view>
			
			<!-- <view v-if="detailData.status == 5">
				<van-button custom-class="left-button" :color="primaryColor" :square="true" size="normal" @click="onClick">重新申请</van-button>
				<van-button custom-class="right-button" :color="secondaryColor" :square="true" size="normal" @click="onClick">取消申请</van-button>
			</view> -->
		</template>
		
		<template v-if="role == 'reviewer'">
			<view v-if="detailData.status == 'created'">
				<van-button custom-class="left-button1" :color="primaryColor" :square="true" size="normal" @click="allowOrRefuse('allowed')">同意申请</van-button>
				<van-button @click="showDisAgreePannel = true" custom-class="right-button2" :color="secondaryColor" :square="true" size="normal">拒绝申请</van-button>
			</view>
		</template>
		
		
		
		
		<template v-if="role == 'controller' && !isThird && !detailData.thirdCompanyId">
			
			<view v-if="detailData.status == 'allowed'" style="margin-top: 20px;">
				<van-button custom-class="left-button" :color="primaryColor" :square="true" size="normal" @click="onDispatch">确认调度</van-button>
				<van-button @click="onCallOhterCompany" custom-class="right-button" :color="secondaryColor" :square="true" size="normal">转派申请</van-button>
			</view>
			
			<view v-if="detailData.status == 'dispatched'" style="margin-top: 20px;">
				<van-button :color="primaryColor" :square="true" size="normal" @click="onDispatch" block>重新调度</van-button>
			</view>
			
		<!-- 	<view v-if="detailData.status == 'travelEnded'" style="margin-top: 20px;">
				<van-button :color="primaryColor" :square="true" size="normal" custom-class="large-mode" @click="onFinishOrder">确认完成</van-button>
			</view> -->
		</template>
		
		<template v-if="role == 'controller' && isThird && detailData.thirdCompanyId">
			
			<view v-if="detailData.status == 'allowed'" style="margin-top: 20px;">
				<van-button custom-class="left-button" :color="primaryColor" :square="true" size="normal" @click="onDispatch">确认调度</van-button>
				<van-button @click="onRefuseDispatch" custom-class="right-button" :color="secondaryColor" :square="true" size="normal">拒绝调度</van-button>
			</view>
			
		<!-- 	<view v-if="detailData.status == 'travelEnded'" style="margin-top: 20px;">
				<van-button :color="primaryColor" :square="true" size="normal" custom-class="large-mode" @click="onFinishOrder">确认完成</van-button>
			</view> -->
			
		</template>
		
		<van-cell-group v-if="detailData.thirdCompanyId" title="三方调度">
			<van-cell title="公司名称" :value="detailData.thirdCompanyName" />
		</van-cell-group>
		
	
		<van-dialog
		  use-slot
		  title="请输入拒绝原因"
		  showCancelButton
		  :show="showDisAgreePannel"
		  @close="showDisAgreePannel = false"
		  @confirm="allowOrRefuse('refused')"
		>
		<view class="disagree-input">
			<textarea maxlength="100"  @input="refuseTextChange"></textarea>
		</view>
		</van-dialog>
		<van-toast id="van-toast" />
		<van-dialog id="van-dialog" />
	</view>
</template>

<script>
	import utils from '@/common/utils.js'
	import Toast from '@/wxcomponents/toast/toast'
	import Dialog from '@/wxcomponents/dialog/dialog'
	export default {
		data() {
			return {
				primaryColor:getApp().globalData.primaryColor,
				secondaryColor: getApp().globalData.secondaryColor,
				showDisAgreePannel: false,
				role: '3',
				detailData:{
					type: 2,
					status: 3,
					num:2
				},
				routeItems:[],
				refuseText: '',
				dataTime:'',
				createTime:'',
				backTime:''
				// noticeReviewEnable: false
			};
		},
		async onLoad(options) {
			console.log(options)
			this.role = options.role
			this.detailData = JSON.parse(decodeURIComponent(options.data))
			uni.setStorageSync('detailData',this.detailData)
			console.log(this.detailData.createTime)
			//预约时间
			let createTime = this.detailData.createTime
			this.createTime = createTime.replace(/-/g, '/')
			//出发时间
			let dataTime = this.detailData.setoffTime
			this.dataTime = dataTime.replace(/-/g, '/')
			//返回时间
			let backTime = this.detailData.backTime
			// console.log(backTime)
			this.backTime = backTime.replace(/-/g, '/')
			// console.log(this.dataTime)
			await this.getDetailData()
			// const detailDataTemp = await utils.req('/order/getOrderDetail', reqData)
		},
		mounted() {
			//get detailData
			if(this.role == 'controller'){
				if(this.detailData.status == 'allowed' || this.detailData.status == 'dispatched' ){
					this.generateRouteItems()
				}
			}
		},
		methods:{
			updata(e){
			 	uni.navigateTo({
			 		url:'../updataMessage/updataMessage?orderid='+ this.detailData.id
			 	})
			},
			onChange(e){
				const type = e.currentTarget.dataset.type
				if(type == 'carNum'){
					this.detailData.num =e.detail
					this.generateRouteItems()
				}
			},
			onCallPhone(e){
				const tel = e.currentTarget.dataset.tel
				Dialog.confirm({
				  title: '提示',
				  message: '确认拨打' + tel + '吗',
				})
			  .then(() => {
				  uni.makePhoneCall({
				  	phoneNumber:tel
				  })
			  })
			  .catch(() => {
				// on cancel
			  });
			},
			onConnectDriver(){
				
			},
			onRedispatch(){
				
			},
			refuseTextChange(event){
				this.refuseText = event.detail.value
			},
			async getDetailData(){
				try{
					const reqData = {
						token: uni.getStorageSync('userinfo').token,
						orderId: this.detailData.id
					}
					const detailDataTemp = await utils.req('/order/getOrderDetail', reqData)
					console.log(detailDataTemp)
					// detailDataTemp.trips = JSON.parse(detailDataTemp.trips)
					// console.log(detailDataTemp.lstCD)
					// const busAndDriver = detailDataTemp.lstCD.filter(o => o.driver.userId == uni.getStorageSync('userinfo').userId)[0]
					// detailDataTemp.zBD = busAndDriver
					// detailDataTemp.zBus=busAndDriver.car
					// detailDataTemp.zDriver=busAndDriver.driver
					// console.log(busAndDriver)
					// detailDataTemp.zDriver=busAndDriver.driver
					this.detailData = Object.assign({}, detailDataTemp, this.detailData)
					console.log(this.detailData)
				}catch(e){
					console.error(e)
					//TODO handle the exception
				}
			},
			generateRouteItems(){
				//根据用车数量生成行程
				const num = this.detailData.requstCarNum
				const routes = []
				for (let i = 0; i < num; i++) {
					routes.push({backIndex: i,driver: {name:'', phone: ''}, bus:{number:''}})
				}
				this.routeItems = routes
			},
			onCallOhterCompany(){
				uni.navigateTo({
					url:'../company-list/company-list?orderid=' + this.detailData.id
				})
			},
			async onFinishOrder(){
				const reqData = {
					token: uni.getStorageSync('userinfo').token,
					orderId: this.detailData.id
				}
				
				Dialog.confirm({
					title: '提示',
					message: '确认是否完成'
				}).then(async() => {
					try{
						uni.showLoading({
							mask:true,
							title:'上传数据中...'
						})
						
						await utils.req('/order/finish', reqData)
						Toast({
						  message: '确认完成成功',
						  onClose: () => {
						    uni.navigateBack({
						    	delta:1
						    })
						  }
						})
						
					}catch(e){
						console.error(e)
						Toast(e.msg)
					}finally{
						uni.hideLoading()
					}
				}).catch(() => {
					// on cancel
				});
			},
			async onRefuseDispatch(){
				const reqData = {
					token: uni.getStorageSync('userinfo').token,
					orderId: this.detailData.id
				}
				
				Dialog.confirm({
					title: '提示',
					message: '确认是否拒绝调度'
				}).then(async() => {
					try{
						uni.showLoading({
							mask:true,
							title:'上传数据中...'
						})
						
						await utils.req('/order/thirdRefuse', reqData)
						Toast({
						  message: '拒绝调度成功',
						  onClose: () => {
						    uni.navigateBack({
						    	delta:1
						    })
						  }
						})
						
					}catch(e){
						console.error(e)
						Toast(e.msg)
					}finally{
						uni.hideLoading()
					}
				}).catch(() => {
					// on cancel
				});
			},
			async onDispatch(){
				const reqData = {
					token: uni.getStorageSync('userinfo').token,
					orderId: this.detailData.id
				}
				reqData.maps = this.routeItems.filter(o => o.bus.carId && o.driver.userId).map(o => { return {
					carId:o.bus.carId,
					userId: o.driver.userId
				}})
				
				if(reqData.maps.length == 0){
					Toast("请选择司机和车辆")
					return
				}
				
				Dialog.confirm({
					title: '提示',
					message: '是否确认提交调度'
				}).then(async() => {
					try{
						uni.showLoading({
							mask:true,
							title:'上传数据中...'
						})
						
						await utils.req('/order/orderController', reqData)
						Toast({
						  message: '调度成功',
						  onClose: () => {
						    uni.navigateBack({
						    	delta:1
						    })
						  }
						})
						
					}catch(e){
						console.error(e)
						Toast(e.msg)
					}finally{
						uni.hideLoading()
					}
				}).catch(() => {
					// on cancel
				});
				
			},
			async onSendMsg(type){
				try{
					const reqData = {
						token: uni.getStorageSync('userinfo').token,
						orderId: this.detailData.id,
						noticeType: type //noticeReview noticeDispatch
					}
					await utils.req('/push/notice', reqData)
					// if(type == 'noticeReview'){
					// 	Toast('提醒成功！')
					// 	this.noticeReviewEnable = true
					// }
					
					// if(type == 'noticeDispatch'){
					// 	Toast('提醒成功！')
					// 	// this.noticeReviewEnable = false
					// }
					Toast('提醒成功！')
				}catch(e){
					Toast(e.msg)
				}
			},
			async cancelOrder(){
				
				Dialog.confirm({
					title: '提示',
					message: '确认是否取消申请'
				}).then(async() => {
					try{
						uni.showLoading({
							mask:true,
							title:'上传数据中...'
						})
						
						const reqData = {
							token: uni.getStorageSync('userinfo').token,
							orderId: this.detailData.id,
						}
						await utils.req('/order/cancle', reqData)
						
						Toast({
						  message: '取消成功',
						  onClose: () => {
						    uni.navigateBack({
						    	delta:1
						    })
						  }
						})
						
					}catch(e){
						console.error(e)
						Toast(e.msg)
					}finally{
						uni.hideLoading()
					}
				}).catch(() => {
					// on cancel
				});
				
			},
			async allowOrRefuse(status){
				if(status == 'refused' && !this.refuseText){
					Toast('拒绝原因必填')
					return
				}
				Dialog.confirm({
					title: '提示',
					message: '确认是否同意申请'
				}).then(async() => {
					try{
						uni.showLoading({
							mask:true,
							title:'上传数据中...'
						})
						
						const reqData = {
							token: uni.getStorageSync('userinfo').token,
							orderId: this.detailData.id,
							status: status,
							refuseReason: this.refuseText
						}
						await utils.req('/order/allowOrRefuse', reqData)
						
						if(status == 'allowed'){
							Toast({
							  message: '审核成功',
							  onClose: () => {
							    uni.navigateBack({
							    	delta:1
							    })
							  }
							})
						}else{
							Toast({
							  message: '审核成功',
							  onClose: () => {
							    uni.navigateBack({
							    	delta:1
							    })
							  }
							})
						}
						
					}catch(e){
						console.error(e)
						Toast(e.msg)
					}finally{
						uni.hideLoading()
					}
				}).catch(() => {
					// on cancel
				});
				
				try{
					
					
				}catch(e){
					Toast(e.msg)
				}
			}
		},
		computed:{
			orderType(){
				if(this.detailData.orderType == 'yuyue'){
					return '预约'
				}else if(this.detailData.orderType == 'jieji'){
					return '接机'
				}else if(this.detailData.orderType == 'songji'){
					return '送机'
				}
			},
			orderStatusText(){
				return utils.statusToText(this.detailData.status)
			},
			isThird(){
				return uni.getStorageSync('userinfo').companyId != 1
			}
		}
	}
</script>

<style lang="scss">
.flow-container{
	background-color: $uni-bg-color;
	padding: 16px;
}
.left-button{
	width: 30%;
	margin-left: 5px;
}
.center-button{
	width: 30%;
	margin-left: 10px;
	margin-right: 10px;
	background-color: #F8F8F8;
}
.right-button{
	width: 30%;
	margin-right: 5px;
	background-color: $uni-color-secondary;
}
.refuse-container{
	background-color: $uni-bg-color;
	padding: 16px;
	word-wrap: break-word;
	color: $uni-text-color-placeholder;
	font-size: 14px;
}
.large-mode{
	width: 100%;
}
.disagree-input{
	margin: 15px;
	border: 1px solid $uni-border-color;
}
.left-button1{
	width: 50%;
}
.right-button2{
	width: 50%;
	background-color: $uni-color-secondary;
}
</style>
